package com.edgarli.gamble.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.edgarli.common.utils.DateUtils;
import com.edgarli.common.utils.DingTalkUtils;
import com.edgarli.common.utils.StringUtils;
import com.edgarli.common.utils.http.HttpUtils;
import com.edgarli.gamble.domain.TLottoHistory;
import com.edgarli.gamble.domain.TLottoNz;
import com.edgarli.gamble.service.ITLottoHistoryService;
import com.edgarli.gamble.service.ITLottoNzService;
import com.edgarli.gamble.service.ITLottoService;
import com.edgarli.quartz.service.GambleService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lixun
 * @Description
 * @create 2024-08-14 17:24
 */
@Service
public class GambleQuartzServiceImpl implements GambleService {
    private static final Logger log = LoggerFactory.getLogger(GambleQuartzServiceImpl.class);

    @Autowired
    ITLottoHistoryService lottoHistoryService;

    @Autowired
    ITLottoNzService lottoNzService;

    @Autowired
    ITLottoService lottoService;

    @Override
    public void grabBigLottoHistory() {
        System.out.println("开始抓取");

        String url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=30&isVerify=1&pageNo=";
        int pageNo = 1;

        while (getLottoHistory(url, pageNo)) {
            pageNo++;
        }
        System.out.println("抓取结束");
        DingTalkUtils.sendMsg("历史大乐透抓取结束");
    }


    @SneakyThrows
    private synchronized boolean getLottoHistory(String url, int pageNo) {

        String data = HttpRequest.get(url + pageNo).header("User-Agent", "").execute().body();
        log.info("成功：");
        JSONObject jsonObject = JSONObject.parseObject(data);
        Map<String, Object> map = jsonObject;
        String value = map.getOrDefault("value", "").toString();
        Map<String, Object> jsonVlaue = JSONObject.parseObject(value);

        String list = jsonVlaue.getOrDefault("list", "").toString();
        JSONArray listArray = JSONObject.parseArray(list);

        List<TLottoHistory> historyList = new ArrayList<>();

        for (Object o : listArray) {
            Map<String, Object> lottMap = JSONObject.parseObject(o.toString());

            log.info("数据" + lottMap.toString());

            TLottoHistory history = new TLottoHistory();
            String lotteryDrawNum = lottMap.getOrDefault("lotteryDrawNum", "").toString();
            history.setPeriods(lotteryDrawNum);
            history.setKjrqDt(DateUtils.parseDate(lottMap.getOrDefault("lotteryDrawTime", "").toString()));
            String lotteryDrawResult = lottMap.getOrDefault("lotteryDrawResult", "").toString();
            history.setNumber(lotteryDrawResult);

            String drawresult = lottMap.getOrDefault("lotteryUnsortDrawresult", "").toString();
            String[] split = new String[]{};
            if (drawresult.split(" ").length < 6) {
                split = lotteryDrawResult.split(" ");
            } else {
                split = drawresult.split(" ");
            }

            log.info("期数" + lotteryDrawNum);
            log.info("顺序前数据" + drawresult);
            log.info("顺序后数据" + lotteryDrawResult);

            history.setN1(split[0]);
            history.setN2(split[1]);
            history.setN3(split[2]);
            history.setN4(split[3]);
            history.setN5(split[4]);
            history.setN6(split[5]);
            history.setN7(split[6]);
            historyList.add(history);
        }
        lottoHistoryService.insertBatch(historyList);

        String pages = jsonVlaue.getOrDefault("pages", "0").toString();
        Thread.sleep(10000);
        log.info(String.format("当前页%s,总页%s", pageNo, pages));

        if (Integer.parseInt(pages) > pageNo) {
            return true;
        }
        return false;
    }

    @Override
    public void grabBigLottoNew() {
        System.out.println("开始抓取");

        String url = "https://webapi.sporttery.cn/gateway/lottery/getDigitalDrawInfoV1.qry?param=85,0&isVerify=1";
        String data = HttpRequest.get(url).header("User-Agent", "").execute().body();
        log.info("成功：");

        JSONObject jsonObject = JSONObject.parseObject(data);
        Map<String, Object> map = jsonObject;
        String value = map.getOrDefault("value", "").toString();
        Map<String, Object> jsonVlaue = JSONObject.parseObject(value);
        String dlt = jsonVlaue.getOrDefault("dlt", "").toString();
        Map<String, Object> dltMap = JSONObject.parseObject(dlt);

        log.info("数据" + dltMap.toString());

        TLottoHistory history = new TLottoHistory();
        String lotteryDrawNum = dltMap.getOrDefault("lotteryDrawNum", "").toString();
        history.setPeriods(lotteryDrawNum);
        history.setKjrqDt(DateUtils.parseDate(dltMap.getOrDefault("lotteryDrawTime", "").toString()));
        String lotteryDrawResult = dltMap.getOrDefault("lotteryDrawResult", "").toString();
        history.setNumber(lotteryDrawResult);

        String drawresult = dltMap.getOrDefault("lotteryUnsortDrawresult", "").toString();
        String[] split = new String[]{};
        if (drawresult.split(" ").length < 6) {
            split = lotteryDrawResult.split(" ");
        } else split = drawresult.split(" ");

        log.info("期数" + lotteryDrawNum);
        log.info("顺序前数据" + drawresult);
        log.info("顺序后数据" + lotteryDrawResult);

        history.setN1(split[0]);
        history.setN2(split[1]);
        history.setN3(split[2]);
        history.setN4(split[3]);
        history.setN5(split[4]);
        history.setN6(split[5]);
        history.setN7(split[6]);
        List<TLottoHistory> historyList = new ArrayList<>();
        historyList.add(history);
        lottoHistoryService.insertBatch(historyList);
        DingTalkUtils.sendMsg("最新大乐透抓取结束");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void grabLottoNz() {
        lottoNzService.deleteAll();
        int front = 35, back = 12, num = 0;
        List<TLottoNz> lottoNzList = new ArrayList<>();
        for (int i = 1; i <= front; i++) {
            for (int j = i + 1; j <= front; j++) {
                for (int k = j + 1; k <= front; k++) {
                    for (int l = k + 1; l <= front; l++) {
                        for (int m = l + 1; m <= front; m++) {
                            for (int n = 1; n <= back; n++) {
                                for (int o = n + 1; o <= back; o++) {
                                    num++;
                                    TLottoNz nz = new TLottoNz();
                                    nz.setN2(String.format("%02d", j));
                                    nz.setN3(String.format("%02d", k));
                                    nz.setN1(String.format("%02d", i));
                                    nz.setN4(String.format("%02d", l));
                                    nz.setN5(String.format("%02d", m));
                                    nz.setN6(String.format("%02d", n));
                                    nz.setN7(String.format("%02d", o));
                                    nz.setNumber(nz.getN1() + " " + nz.getN2() + " " + nz.getN3() + " " + nz.getN4() + " " + nz.getN5() + " " + nz.getN6() + " " + nz.getN7());
                                    log.info("生成结果" + nz.getNumber());
                                    lottoNzList.add(nz);
                                    if (lottoNzList.size() >= 1000000) {
                                        lottoNzService.saveBatch(lottoNzList);
                                        lottoNzList.clear();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        log.info(String.format("生成%s个内置数据", num));
        lottoNzService.saveBatch(lottoNzList);
    }

    @Override
    public void updateLottoNz() {
        lottoNzService.updateNumAboutHidtory();
        DingTalkUtils.sendMsg("内置大乐透刷新成功");
    }

    @Override
    public void estimateLotto() {
        lottoService.estimate();
        DingTalkUtils.sendMsg("大乐透预估成功");
    }

}
